package com.durian.base.utils;

import android.app.Activity;
import androidx.lifecycle.Lifecycle;

import android.app.Application;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Build;
import android.os.Looper;
import android.provider.Settings;
import androidx.appcompat.app.AppCompatActivity;
import android.text.format.Formatter;

import com.durian.BaseApp;
import com.durian.base.permission.FileProvider;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 说明：ToolUtils
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2019-06-17 20:22
 * <p/>
 * 版本：version 1.0
 */
public class ToolUtils {

    public static boolean isResumed(AppCompatActivity activity){
        boolean isResumed = false;
        if (activity != null && activity.getLifecycle().getCurrentState() == Lifecycle.State.RESUMED){
            isResumed = true;
        }
        return isResumed;
    }

    public static boolean isResumed(WeakReference<AppCompatActivity> activity){
        boolean isResumed = false;
        if (activity != null
                && activity.get() != null
                && activity.get().getLifecycle().getCurrentState() == Lifecycle.State.RESUMED){
            isResumed = true;
        }
        return isResumed;
    }

    /**
     * 判断当前activity是否是透明的
     * @param activity
     * @return
     */
    public static boolean isTranslucentActivity(Activity activity){
        boolean isTranslucent = false;
        TypedArray array;
        try {
            int []attr = new int[]{android.R.attr.windowIsTranslucent};
            array = activity.getTheme().obtainStyledAttributes(attr);
            isTranslucent = array.getBoolean(0,false);
        }catch (Exception e){
            e.printStackTrace();
        }
        return isTranslucent;
    }

    public static void toFinish(Activity activity){
        if (isNotFinish(activity)){
            activity.finish();
        }
    }

    /**
     * 页面没有关闭
     * @param activity
     * @return
     */
    public static boolean isNotFinish(Activity activity){
        if (activity == null || activity.isFinishing()){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 打开txt
     * @param file
     */
    public static void openText(Uri file){
        openFile(file, "text/*");
    }

    /**
     * 打开文件
     * @param uri
     * @param type
     */
    public static void openFile(Uri uri,String type){
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(uri,type);
            Application application = BaseApp.getApp();
            if (application == null){
                return;
            }
            application.startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 打开应用设置
     * @param context
     */
    public static void openAppSetting(Context context){
        try {
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            Uri uri = Uri.fromParts("package", context.getPackageName(), null);
            intent.setData(uri);
            context.startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 说明：使用浏览器打开
     */
    public static void openBrowser(Activity activity, String url){
        try {
            if (StringUtils.isEmpty(url) || activity == null){
                return;
            }
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            activity.startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 说明：安装apk
     *
     * @param context
     * @param file
     */
    public static boolean installApk(Context context, File file) {
        boolean result = false;
        try {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setType("application/vnd.android.package-archive");
            intent.setData(Uri.fromFile(file));
            intent.setDataAndType(Uri.fromFile(file),
                                  "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            result = true;
        }catch (Exception e){
        }finally {
            return result;
        }
    }

    /**
     * 说明：拨打电话号码
     *
     * @param number 电话号码
     */
    public static void callPhone(Context context, String number) {
        try {
            Uri uri = Uri.parse("tel:" + number);
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(uri);
            context.startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 说明：判断是否是UI线程
     * @return
     */
    public static boolean isMainThread(){
        return Looper.myLooper() == Looper.getMainLooper();
    }

    /**
     * 说明：刷新图库
     *
     * @param context
     * @param file
     */
    public static void refreshPic(Context context, File file) {
        try {
            // 最后通知图库更新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 说明：文件单位转换B->KB->MB->GB
     *
     * @param context
     * @param size
     * @return
     */
    public static String formatFileSize(Context context, long size) {
        return Formatter.formatFileSize(context, size);
    }

    /**
     * 说明：执行command命令，返回文本
     *
     * @param command 命令
     * @return 字符串
     */
    public static String cmdForResult(String command) {
        StringBuilder sb = new StringBuilder();
        DataOutputStream dos = null;
        BufferedReader reader = null;
        try {
            Process process = Runtime.getRuntime().exec("su");
            dos = new DataOutputStream(process.getOutputStream());
            dos.writeBytes(command + "\n");
            dos.flush();
            dos.writeBytes("exit\n");
            dos.flush();

            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } finally {
            FileUtils.closeIO(dos, reader);
        }
    }

    /**
     * 说明：将文本内容复制到剪切板中
     *
     * @param context
     * @param content 要复制的内容
     */
    public static boolean copyText(Context context, String content) {
        try {
            if (content == null || content == null) {
                return false;
            } else {
                ClipboardManager clip = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                clip.setPrimaryClip(ClipData.newPlainText(null, content));
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 说明：获取错误信息
     *
     * @return
     */
    public static String collectErrorInfo(Throwable ex) {
        Application application = BaseApp.getApp();
        if (application == null){
            return "";
        }
        Map<String, String> infos = new HashMap<String, String>();
        try {
            PackageManager pm = application.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(application.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null"
                        : pi.versionName;
                String versionCode = pi.versionCode + "";
                infos.put("versionName", versionName);
                infos.put("versionCode", versionCode);
            }
        } catch (Exception e) {
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                infos.put(field.getName(), field.get(null).toString());
            } catch (Exception e) {
            }
        }

        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        sb.append(writer.toString());
        return sb.toString();
    }

    /**
     * Get compatible Android 7.0 and lower versions of Uri.
     *
     * @param context {@link Context}.
     * @param file    apk file.
     * @return uri.
     */
    public static Uri getFileUri(Context context, File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return FileProvider.getUriForFile(context, context.getPackageName() + ".file.path.share", file);
        }
        return Uri.fromFile(file);
    }
}
